from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from src.database import close_db, init_db
from src.middlewares import UserAuthMiddleware
from src.routers import routers


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用程序生命周期管理"""
    # 启动时初始化数据库
    await init_db()
    print("Database initialized")

    yield

    # 关闭时清理数据库连接
    await close_db()
    print("Database connections closed")


app = FastAPI(
    title="Allhome API",
    description="基于 FastAPI 的异步 Web 应用",
    version="0.1.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_middleware(UserAuthMiddleware)

# 包含路由
for router in routers:
    app.include_router(router, prefix="/api/v1")


@app.get("/")
async def read_root():
    """根路径"""
    return {"message": "Welcome to Allhome API", "version": "0.1.0"}


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "message": "All systems operational"}
